package com.zhangmeng.online.exam.controller;

import com.zhangmeng.online.exam.dao.PermissionDao;
import com.zhangmeng.online.exam.dto.Result;
import com.zhangmeng.online.exam.entity.Permission;
import com.zhangmeng.online.exam.entity.Role;
import com.zhangmeng.online.exam.utils.PageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zm
 * @date 2025/3/7 9:46
 * @version: 1.0
 */
@RestController
@RequestMapping("/permission")
public class PermissionController {

    @Autowired
    private PermissionDao permissionDao;

    /**
     * // 基本分页（无排序）
     * Pageable pageable = PageRequest.of(0, 10);
     * <p>
     * // 分页+排序（单字段）
     * Pageable pageable = PageRequest.of(0, 10, Sort.Direction.DESC, "createTime");
     * <p>
     * // 分页+多字段排序
     * Sort sort = Sort.by(Sort.Order.asc("age"), Sort.Order.desc("name"));
     * Pageable pageable = PageRequest.of(0, 10, sort);
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping("/list")
    public Result list(Integer pageNum, Integer pageSize, boolean isTop) {

        Pageable pageable = PageRequest.of(PageUtils.getPageNum(pageNum), pageSize, Sort.Direction.DESC, "addTime");

        Page<Permission> all;
        if (isTop) {
            Specification<Permission> spec = isDescriptionNull(); // 仅查询description为null的情况
            all = permissionDao.findAll(spec, pageable);
        } else {
            all = permissionDao.findAll(pageable);
        }

        List<Permission> list = all.getContent();
        List<Map<String, Object>> resultList = new ArrayList<>();
        for (Permission permission : list) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", permission.getId());
            map.put("name", permission.getName());
            map.put("desc", permission.getDescription());
            map.put("url", permission.getUrl());
            map.put("sort", permission.getSort());
            map.put("parentId", permission.getParent() == null ? 0L : permission.getParent().getId());

            resultList.add(map);
        }
        return Result.success(pageNum, pageSize, all.getTotalElements(), resultList);
    }

    @RequestMapping("/save")
    public Result save(@RequestParam @RequestBody Map<String, Object> params, HttpServletRequest request) {
        Permission permission;
        Map<String, String[]> parameterMap = request.getParameterMap();

        String id = params.get("id").toString();
        String name = params.get("name").toString();
        String description = params.get("description").toString();
        String url = params.get("url").toString();
        String parent_id = params.get("parent_id").toString();

        if (id != null && !id.isEmpty()) {
            permission = permissionDao.getById(Long.parseLong(id));
        } else {
            permission = new Permission();
        }
        permission.setName(name);
        permission.setDescription(description);
        permission.setUrl(url);
        if (parent_id != null && !parent_id.isEmpty()) {
            permission.setParent(permissionDao.getById(Long.parseLong(parent_id)));
        }
        permissionDao.save(permission);

        return Result.success(null);
    }

    public Specification<Permission> isDescriptionNull() {
        return (root, query, cb) -> cb.isNull(root.get("parent"));
    }


    @RequestMapping("/getPermissionById")
    public Result getPermissionById(Long id) {
        Permission permission = permissionDao.getById(id);
        Map<String, Object> map = new HashMap<>();
        map.put("id", permission.getId());
        map.put("name", permission.getName());
        map.put("desc", permission.getDescription());
        map.put("url", permission.getUrl());
        map.put("sort", permission.getSort());
        map.put("parentId", permission.getParent() == null ? 0L : permission.getParent().getId());

        return Result.success(map);
    }

    @RequestMapping("/getRootPermissions")
    public Result getRootPermissions() {
        Specification<Permission> spec = isDescriptionNull(); // 仅查询description为null的情况
        List<Permission> all = permissionDao.findAll(spec);
        List<Map<String, Object>> resultList = new ArrayList<>();
        for (Permission permission : all) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", permission.getId());
            map.put("name", permission.getName());
            map.put("desc", permission.getDescription());
            map.put("url", permission.getUrl());
            map.put("sort", permission.getSort());

            List<Map<String, Object>> childList = new ArrayList<>();
            for (Permission child : permission.getChildren()) {
                Map<String, Object> childMap = new HashMap<>();
                childMap.put("id", child.getId());
                childMap.put("name", child.getName());
                childMap.put("desc", child.getDescription());
                childMap.put("url", child.getUrl());
                childMap.put("sort", child.getSort());
                childMap.put("parentId", child.getParent() == null ? 0L : child.getParent().getId());
                childList.add(childMap);
            }
            map.put("children", childList);

            resultList.add(map);
        }
        return Result.success(resultList);
    }

    @RequestMapping("/delete")
    public Result delete(Long id) {
        permissionDao.deleteById(id);
        return Result.success(null);
    }
}
